//
//  XMNetworkManager.m
//  TestView
//
//  Created by lk@wxm on 2024/12/4.
//
#import <Foundation/Foundation.h>
#import "XMNetworkManager.h"

@implementation XMNetworkManager
+ (XMNetworkManager *)shared{
    static XMNetworkManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[XMNetworkManager alloc]init];
    });
    return manager;
}
- (void)performGETRequest:(NSString *)Url andComplet:(void(^)(NSArray*array,NSError*error)) Complete{
    NSURL *url = [NSURL URLWithString:@"https://jsonplaceholder.typicode.com/posts"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData * _Nullable data,
                                                                    NSURLResponse * _Nullable response,
                                                                    NSError * _Nullable error) {
        if (error) {
            NSLog(@"Error: %@", error.localizedDescription);
        } else {
            // 处理响应数据
            NSError *jsonError;
            NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data
                                                                  options:NSJSONReadingAllowFragments
                                                                    error:&jsonError];
            if (jsonError) {
                NSLog(@"JSON Error: %@", jsonError.localizedDescription);
            } else {
                NSLog(@"Response: %@", jsonArray);
            }
        }
    }];
    
    [dataTask resume];  // 启动请求
}

- (void)performPOSTRequest:(NSString *)Url andComplet:(void(^)(NSDictionary*dic,NSError*error)) Complete {
    NSURL *url = [NSURL URLWithString:@"https://jsonplaceholder.typicode.com/posts"];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    
    NSDictionary *parameters = @{@"title": @"foo", @"body": @"bar", @"userId": @1};
    NSError *error;
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:parameters
                                                       options:0
                                                         error:&error];
    [request setHTTPBody:bodyData];
    
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData * _Nullable data,
                                                                    NSURLResponse * _Nullable response,
                                                                    NSError * _Nullable error) {
        if (error) {
            NSLog(@"Error: %@", error.localizedDescription);
        } else {
            // 处理响应数据
            NSError *jsonError;
            NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data
                                                                     options:NSJSONReadingAllowFragments
                                                                       error:&jsonError];
            if (jsonError) {
                NSLog(@"JSON Error: %@", jsonError.localizedDescription);
            } else {
                NSLog(@"Response: %@", jsonDict);
            }
        }
    }];
    
    [dataTask resume];  // 启动请求
}


- (void)downloadFileFromURL:(NSURL *)url toDestination:(NSURL *)destinationURL {
    // 创建 NSURLSession 和 NSURLSessionDownloadTask
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:url];
    [downloadTask resume];  // 启动下载任务
}

#pragma mark - NSURLSessionDownloadDelegate

// 下载进度更新
- (void)URLSession:(NSURLSession *)session
                  downloadTask:(NSURLSessionDownloadTask *)downloadTask
                  didWriteData:(int64_t)bytesWritten
                  totalBytesWritten:(int64_t)totalBytesWritten
                  totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    
    // 计算下载进度
    double progress = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;
    NSLog(@"Download Progress: %.2f%%", progress * 100);
}

// 下载完成
- (void)URLSession:(NSURLSession *)session
                  downloadTask:(NSURLSessionDownloadTask *)downloadTask
                  didFinishDownloadingToURL:(NSURL *)location {
    // 下载成功，移动文件到目标位置
    NSError *error;
    [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL URLWithString:kPathDocument] error:&error];
    if (error) {
        NSLog(@"Error moving file: %@", error.localizedDescription);
    } else {
        NSLog(@"File downloaded to: %@", kPathDocument);
    }
}

// 下载失败
- (void)URLSession:(NSURLSession *)session
                  downloadTask:(NSURLSessionDownloadTask *)downloadTask
                  didFailWithError:(NSError *)error {
    NSLog(@"Download failed: %@", error.localizedDescription);
}
@end
